package com.example.demo.controller;

import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.entity.Order;
import com.example.demo.model.Result;
import com.example.demo.repository.OrderDao;
import com.jiangwz.utils.RedisUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 订单测试控制器
 * @author jiangwz
 * @create 2019/10/24.
 */
@RequestMapping("/order")
@RestController
@Slf4j
public class OrderController {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 添加订单
     * 1. 加redis锁是为了以防止用户提交订单冲突,多提交了几份
     * @param order
     * @return
     */
    @PostMapping
    public Object add(@RequestBody Order order){
        log.info("order {}",order);
        Assert.notNull(order.getUserId(),"用户id不能为空");
        String key= "order:userId:"+ order.getUserId();
        String value = UUID.randomUUID().toString();
        boolean lock = redisUtil.setNx(key, value, 2);
        if (lock) {
            orderDao.save(order);
            // 不需要解锁,因为解锁会让其他慢的线程继续获取到锁
        }
        return Result.ok();
    }

}
